//
//  ZZTFastTransfer.m
//  HPZZTong
//
//  Created by WenJun on 14-7-11.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "ZZTFastTransfer.h"
//#import "HPUIEngine.h"
//#import "CSNValidator.h"
//#import "ZZTongClientEngine.h"
//#import "POSUIEngine.h"

@interface POSProcess()

- (void)encryptData;

@end

@implementation ZZTFastTransfer

- (void)beginWithDelegate:(id)delegate
{
//    [CSNValidator validateCSNAndExcuteBlock:^(HPSwiperResult *swiperResult) {
//        if (swiperResult.isSuccess)
//        {
//            [super beginWithDelegate:delegate];
//        }
//    } autoTip:YES];
    // marco modify
    [super beginWithDelegate:delegate];
}

- (id)init
{
    self = [super init];
    _plainCurrency = @"156";
//    self.uiDelegate = POSUIENG;
    return self;
}
- (void)padding:(NSMutableString *)output str:(NSString *)str{
    [output appendString:str];
    int l = [str length] % 8;
    if (l > 0) {
        l = 8 - l;
        for (int i = 0; i < l; i++) {
            [output appendString:@"\0"];
        }
    }
}
- (NSString *)parseEncElement:(NSString *)input index:(int *)index len:(int)len{
    int l = len % 8;
    if (l > 0) {
        len += (8 - l);
    }
    
    len *= 2;
    if (*index + len > [input length]) {
        return nil;
    }
    
    NSString* ret = [input substringWithRange:NSMakeRange(*index, len)];
    *index += len;
    return ret;
}

- (void)encryptData{
    if (!self.encAccount2)
    {
        NSMutableString* tempStr = [[NSMutableString alloc] init];
        
        [self padding:tempStr str:self.plainTerminalID];
        [self padding:tempStr str:self.plainAccount2];
        [self padding:tempStr str:self.plainCurrency];
        
        [self setValue:[NSNumber numberWithInt:SwipeActionEncrypt] forKeyPath:@"currentAction"];
        [self.currentSwiper encryptKeyData:tempStr factor:self.factor complete:^(HPSwiperResult *swiperResult) {
            if (swiperResult.isSuccess)
            {
                NSString *allCodeStr = swiperResult.value;
                int index = 0;
                
                NSString *terminalID = [self parseEncElement:allCodeStr index:&index len:(int)self.plainTerminalID.length];
                NSString *account2 = [self parseEncElement:allCodeStr index:&index len:(int)self.plainAccount2.length];
                NSString *plainCur = [self parseEncElement:allCodeStr index:&index len:(int)self.plainCurrency.length];
                
                [self setValue:terminalID forKeyPath:@"encTerminalID"];
                [self setValue:account2 forKeyPath:@"encAccount2"];
                [self setValue:plainCur forKeyPath:@"encCurrency"];
                [super encryptData];
            }
            else
            {
                [self dealResult:swiperResult];
            }
        }];
    }
}
@end
